package auralvm

import (
	"fmt"
	"html/template"
	"net/http"
	"net/url"

	"code.google.com/awwwe-browser/auralvm/conversation"
	"code.google.com/awwwe-browser/auralvm/param"
)

// template data
type StartData struct {
	URL                                template.HTMLAttr
	Package                            template.JSStr
	ConversationTypeOptions            conversation.ConversationType
	ConversationTypeLinks              conversation.ConversationType
	ConversationTypeTexts              conversation.ConversationType
	ConversationTypeFormEnterText      conversation.ConversationType
	ConversationTypeFormSingleSelect   conversation.ConversationType
	ConversationTypeFormMultipleSelect conversation.ConversationType
	ConversationTypeYesNo              conversation.ConversationType
	ConversationTypeVideos             conversation.ConversationType
	ConversationTypeVideo              conversation.ConversationType
	TextInputId                        template.HTMLAttr
	VideoId                            template.HTMLAttr
}

func newStartData() *StartData {
	var v StartData
	var u url.URL
	u.Scheme = param.Scheme
	u.Host = fmt.Sprintf("%s:%d", param.Host, param.Port)
	u.Path = param.StartPath
	v.URL = template.HTMLAttr(u.String())
	v.Package = template.JSStr(param.Package)
	v.ConversationTypeOptions = conversation.ConversationTypeOptions
	v.ConversationTypeLinks = conversation.ConversationTypeLinks
	v.ConversationTypeTexts = conversation.ConversationTypeTexts
	v.ConversationTypeFormEnterText = conversation.ConversationTypeFormEnterText
	v.ConversationTypeFormSingleSelect = conversation.ConversationTypeFormSingleSelect
	v.ConversationTypeFormMultipleSelect = conversation.ConversationTypeFormMultipleSelect
	v.ConversationTypeYesNo = conversation.ConversationTypeYesNo
	v.ConversationTypeVideos = conversation.ConversationTypeVideos
	v.ConversationTypeVideo = conversation.ConversationTypeVideo
	v.TextInputId = template.HTMLAttr("AWWWEInput")
	v.VideoId = template.HTMLAttr("AWWWEVideo")
	return &v
}

func HandlerStartTestBrowser(w http.ResponseWriter, r *http.Request) {
	var sdata *StartData
	var t *template.Template
	var err error
	sdata = newStartData()
	// page template
	t, err = template.ParseFiles("testbrowser.tmpl")
	if err == nil {
		err = t.Execute(w, sdata)
		if err != nil {
			fmt.Fprint(w, "<html><head><title>Error</title></head><body><h1>Error</h1></body></html>")
		}
	}
}

func HandlerStartAWWWEBrowser(w http.ResponseWriter, r *http.Request) {
	var sdata *StartData
	var t *template.Template
	var err error
	sdata = newStartData()
	// page template
	t, err = template.ParseFiles("awwwebrowser.tmpl")
	if err == nil {
		err = t.Execute(w, sdata)
		if err != nil {
			fmt.Fprint(w, fmt.Sprintf("<html><head><title>Error</title></head><body><h1>Error</h1><p>%s</p></body></html>", err.Error()))
		}
	}
}
